package com.baizhi;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CalNumRunnable implements Runnable {
    private int sum=0;
    Lock lock = new ReentrantLock();//创建出一个锁。可重入锁。
    @Override
    public void run() {
        for(int i=0;i<1000000;i++){
            boolean b = lock.tryLock();//获取到锁对象,返回值表示该线程释放获取到了锁对象
            //synchronized (this) {
            try {
                sum++;
            }finally {
                lock.unlock();//运行完同步代码后，释放锁
            }
            //}

            System.out.println(sum);
        }
    }


    public static void main(String[] args) {
        CalNumRunnable cnr=new CalNumRunnable();
        Thread t1=new Thread(cnr);
        Thread t2=new Thread(cnr);
        Thread t3=new Thread(cnr);
        t1.start();
        t2.start();
        t3.start();
    }
}
